/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import com.sun.lwuit.Command;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;
import entidade.Estado;
import entidade.MobCatController;
import exceptions.ReturnWsException;
import form.components.EstadoListRenderer;

/**
 *
 * @author victorinox
 */
public class EstadoForm extends AbstractForm {

    private List list;
    private final AbstractForm retForm;
    private CidadeForm nextForm = new CidadeForm(this);
    private int lastEstadoId = -1;

    public EstadoForm(AbstractForm returnForm) {
        super("Escolha o estado");
        this.retForm = returnForm;
        try {

            list = new List(MobCatController.getInstance().listEstados());

        } catch (ReturnWsException ex) {
            ex.showError(retForm);
            return;
        }
        list.setListCellRenderer(new EstadoListRenderer());
        addComponent(list);
        list.setSmoothScrolling(true);
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        addCommand(new Command("Voltar") {

            public void actionPerformed(ActionEvent evt) {

                retForm.show();
            }
        });

        list.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                WaitForm.getInstance().show();
                new Thread(new Runnable() {

                    public void run() {
                        listAction();
                    }

                }).start();
            }
        });
    }

    private void listAction() {

        Estado estado = (Estado) list.getSelectedItem();
        if (lastEstadoId == -1 || lastEstadoId != estado.id) {
            lastEstadoId = estado.id;
            nextForm.show(estado.id);
        } else {
            nextForm.show();
        }
    }

    public void show() {
        super.show();
        list.setSelectedIndex(0);
        setFocused(list);
        list.setFocus(true);
        WaitForm.getInstance().setVisible(false);
    }
}

